import networkx as nx
import matplotlib.pyplot as plt
import wiki_parser as wk

def draw_erdos_graph():
  er = nx.erdos_renyi_graph(1000, 0.15)
  nx.draw(er)
  plt.show()
  draw_degree_histogram(er)

def draw_degree_histogram(graph):
  degrees = map(lambda n: graph.degree(n), graph.nodes())
  plt.hist(degrees, bins = 20)
  plt.show()

def generate_graph_from_words(words):
  G = nx.Graph()
  G.add_nodes_from(words)
  for i, word in enumerate(words):
    if i > 0:
      G.add_edge(word, words[i-1])
  return G

def lemmatized_wiki_analysis():
  print("Wiki Lemmatized Analysis")
  fdist, words = wk.get_fdist_and_stems()
  graph = generate_graph_from_words(words)

  print("Number of nodes = %d " % len(graph.nodes()))
  print("Average clustering = %f" % nx.average_clustering(graph))
  print("Diameter = %d" % nx.diameter(graph))

def nonlemmatized_wiki_analysis():
  print("Wiki NonLemmatized Analysis")
  fdist, tokens = wk.get_fdist_and_tokens()
  graph = generate_graph_from_words(tokens)
  
  print("Number of nodes = %d " % len(graph.nodes()))
  print("Average clustering = %f" % nx.average_clustering(graph))
  print("Diameter = %d" % nx.diameter(graph))


def closure_graph(synset, fn):
  seen = set()
  #graph = nx.DiGraph()
  graph = nx.Graph()

  def recurse(s):
    if not s in seen:
        seen.add(s)
        graph.add_node(s.name)
        for s1 in fn(s):
            graph.add_node(s1.name)
            graph.add_edge(s.name, s1.name)
            recurse(s1)

  recurse(synset)
  return graph


def words_to_synsets(words):
  res = []
  for w in words:
    res.append(wn.lemmas(w)[0].synset)
  
  return res  

def ejercicio_5(ss = (wn.all_synsets('n')), fn = (lambda s: s.hypernyms())):

  seen = set()
  #graph = nx.DiGraph()
  graph = nx.Graph()
  
  def recurse(s):
    if not s in seen:
      seen.add(s)
      graph.add_node(s.name)
      for s1 in fn(s):
        graph.add_node(s1.name)
        graph.add_edge(s.name, s1.name)
        recurse(s1)

  for s in ss:  
    #s.hypernym_paths()
    #    
    recurse(s)
    
  return graph  
  # graph = closure_graph(s,
  #                    )


  nx.draw(graph)
  plt.show()





def main():
  #draw_erdos_graph()
  lemmatized_wiki_analysis()
  nonlemmatized_wiki_analysis()

if __name__ == "__main__":
  main()